﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace WebApi.Core.Service.Middleware
{
    public class UnifiedResponseMiddleware
    {
        private readonly RequestDelegate _next;
        ILogger<UnifiedResponseMiddleware> _logger;
        public UnifiedResponseMiddleware(RequestDelegate next,ILogger<UnifiedResponseMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);

                // 处理非认证相关的401响应（如手动返回的401）
                if (context.Response.StatusCode == StatusCodes.Status401Unauthorized && !context.Response.HasStarted)
                { 
                    await HandleResponseAsync(context, 403, "访问未经授权");
                } 
            }
            catch (Exception ex)
            { 
                _logger.LogError(ex, "全局异常"); 
                await HandleResponseAsync(context, 500, "服务器内部错误", ex.Message); 
            }
        }

        private static Task HandleResponseAsync(HttpContext context, int code, string message, string? detail = null)
        {
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = code;

            return context.Response.WriteAsync(JsonSerializer.Serialize(new
            {
                code = code,
                message = message,
                data = detail != null ? new { detail } : null
            }));
        }
         
    }
}
